package io.github.uicdb.et.attachment;

import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import io.github.uicdb.et.element.BasicElement;
import lombok.RequiredArgsConstructor;
import org.checkerframework.common.value.qual.IntRange;
import org.jetbrains.annotations.NotNull;

import java.util.HashMap;
import java.util.Map;


public class ReflectionCD {
    public static final Codec<ReflectionCD> CODEC = RecordCodecBuilder.create(ins -> ins.group(
            Codec.unboundedMap(Codec.STRING, Codec.INT).fieldOf("cdMaps").forGetter(o -> o.cdMaps)
    ).apply(ins, ReflectionCD::new));
    private final Map<String, Integer> cdMaps;

    public ReflectionCD(Map<String, Integer> cdMaps) {
        this.cdMaps = new HashMap<>(cdMaps);
    }

    public int getCd(String key) {
        return cdMaps.getOrDefault(key, 0);
    }

    protected String getKey(BasicElement element1, BasicElement element2) {
        return element1.getElementalObject().getKey().getPath() + "_" + element2.getElementalObject().getKey().getPath();
    }

    public int getCd(BasicElement element1, BasicElement element2) {
        return cdMaps.getOrDefault(getKey(element1, element2), 0);
    }

    public void setCd(@NotNull String key, @IntRange(from = 0) int cd) {
         cdMaps.put(key, cd);
    }

    public void setCd(BasicElement element1, BasicElement element2, @IntRange(from = 0) int cd) {
         cdMaps.put(getKey(element1, element2), cd);
    }

    public void tick() {
        for (Map.Entry<String, Integer> entry : cdMaps.entrySet()) {
            if (entry.getValue() > 0) {
                entry.setValue(entry.getValue() - 1);
            }
        }
    }
}
